<template>
  <div>
    <el-button type="primary" size="mini" @click="useWebFun">使用网络图片</el-button>
    <div v-if="useWebImg" class="web-img-box">
      <el-input type="text" v-model="imageUrl" autocomplete="off">

        <el-button slot="append" icon="el-icon-circle-check" @click="sendImageURL">确认</el-button>
      </el-input>
    </div>
    
    <el-upload v-else
            class="avatar-uploader"
            :action="imgServer+'/users/upload/img'"
            name="icon"
            :headers="headerObj"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
  </div>

</template>

<script>
export default {
    props:{
        imgHref:String
    },
    data(){
        return {
            useWebImg:false,
            imgServer:process.env.VUE_APP_IMG_SERVER,
            headerObj:{
                Authorization:'Bearer '
            },
            imageUrl:'', // 图片临时地址
        }
    },
    methods:{
      useWebFun(){
          this.useWebImg = !this.useWebImg;
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);  // imageUrl 用来临时显示图片地址

        this.$emit('send',res.data);
        
        
      },
      sendImageURL(){
        this.$emit('send',this.imageUrl);
      },
      beforeAvatarUpload(file) {
        
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return  isLt2M;
      },
    },
    watch:{
        'imgHref':{
            immediate:true,
            handler(newVal){
                this.imageUrl = newVal;
                this.useWebImg = this.imgHref?.startsWith('https');
            }
        }
    },
    mounted(){
        // console.log('图片组件调用了');
        // console.log(this.imgHref,'图片地址2');
        // this.imageUrl = this.imgHref;
        let token = localStorage.getItem('token');
        this.headerObj = {
             Authorization:'Bearer '+token
        }
    }
}
</script>

<style  lang="scss">  
 
 .avatar-uploader .el-upload {
     border: 1px dashed #d9d9d9;
     border-radius: 6px;
     cursor: pointer;
     position: relative;
     overflow: hidden;
   }
   .avatar-uploader .el-upload:hover {
     border-color: #409EFF;
   }
   .avatar-uploader-icon {
     font-size: 28px;
     color: #8c939d;
     width: 128px!important;
     height: 128px!important;
     line-height: 128px;
     text-align: center;
     position: relative;
     &::before {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
     }
   }
   .avatar {
     width: 128px;
     height: 128px;
     display: block;
   }

   .web-img-box .el-icon-circle-check {
    font-size: 15px;
   }
</style>